package com.ruoyi.cqjd.controller;

import java.util.List;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.ruoyi.common.core.domain.R;
import com.ruoyi.cqjd.common.BaseContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.cqjd.domain.CqjdAddressBook;
import com.ruoyi.cqjd.service.ICqjdAddressBookService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 地址管理Controller
 * 
 * @author ruoyi
 * @date 2022-06-19
 */
@Slf4j
@RestController
@RequestMapping("/cqjd/cqjd_address_book")
public class CqjdAddressBookController extends BaseController
{
    @Autowired
    private ICqjdAddressBookService cqjdAddressBookService;



    /**
     * 根据id查询地址
     */
    @GetMapping("/front/{id}")
    public R get(@PathVariable Long id) {
        CqjdAddressBook addressBook = cqjdAddressBookService.selectCqjdAddressBookById(id);
        if (addressBook != null) {
            return R.ok(addressBook);
        } else {
            return R.fail("没有找到该对象");
        }
    }


    /**
     * 查询指定用户的全部地址
     */
    @GetMapping("/front_list")
    public R<List<CqjdAddressBook>> frontList(CqjdAddressBook addressBook,HttpSession session) {
        Long userId = (Long) session.getAttribute("user");
        addressBook.setUserId(userId);
//        addressBook.setUserId(BaseContext.getCurrentId());
        log.info("addressBook:{}", addressBook);

        //条件构造器
//        LambdaQueryWrapper<AddressBook> queryWrapper = new LambdaQueryWrapper<>();
//        queryWrapper.eq(null != addressBook.getUserId(), AddressBook::getUserId, addressBook.getUserId());
//        queryWrapper.orderByDesc(AddressBook::getUpdateTime);
        List<CqjdAddressBook> list = cqjdAddressBookService.getAddressListByUserId(userId);


        //SQL:select * from address_book where user_id = ? order by update_time desc
        return R.ok(list);
    }

    /**
     * 新增
     */
    @PostMapping("/front_save")
    public R<CqjdAddressBook> save(@RequestBody CqjdAddressBook addressBook,HttpSession session) {
        Long userId = (Long) session.getAttribute("user");

        addressBook.setUserId(userId);
        log.info("addressBook:{}", addressBook);
        cqjdAddressBookService.insertCqjdAddressBook(addressBook);
        return R.ok(addressBook);
    }



    /**
     * 设置默认地址
     */
    @PutMapping("/front/default")
    public R<CqjdAddressBook> setDefault(@RequestBody CqjdAddressBook addressBook,HttpSession session) {
        log.info("addressBook:{}", addressBook);
//        LambdaUpdateWrapper<AddressBook> wrapper = new LambdaUpdateWrapper<>();
//        wrapper.eq(AddressBook::getUserId, BaseContext.getCurrentId());
//        wrapper.set(AddressBook::getIsDefault, 0);
//        //SQL:update address_book set is_default = 0 where user_id = ?
//        addressBookService.update(wrapper);

        Long userId = (Long) session.getAttribute("user");

        addressBook.setUserId(userId);

        cqjdAddressBookService.updateAddressBookDefaultIsOffByUserId(userId);

        addressBook.setIsDefault(1);
        //SQL:update address_book set is_default = 1 where id = ?
//        addressBookService.updateById(addressBook);
        cqjdAddressBookService.updateCqjdAddressBook(addressBook);
        return R.ok(addressBook);
    }


    /**
     * 删除地址
     */
    @DeleteMapping("/front/delete")
    public R delete(Long[] ids) {
//        LambdaQueryWrapper<AddressBook> queryWrapper = new LambdaQueryWrapper<>();
//        queryWrapper.eq(AddressBook::getUserId, BaseContext.getCurrentId());
//        queryWrapper.eq(AddressBook::getIsDefault, 1);
//
//        //SQL:select * from address_book where user_id = ? and is_default = 1
//        AddressBook addressBook = addressBookService.getOne(queryWrapper);
//
//        if (null == addressBook) {
//            return R.error("没有找到该对象");
//        } else {
//            return R.success(addressBook);
//        }
        cqjdAddressBookService.deleteCqjdAddressBookByIds(ids);
        return R.ok();
    }

    /**
     * 编辑收货地址
     */
    @PutMapping("/front_edit")
    public R  edit(@RequestBody CqjdAddressBook addressBook,HttpSession session) {
//        log.info("addressBook:{}", addressBook);
//        LambdaUpdateWrapper<AddressBook> wrapper = new LambdaUpdateWrapper<>();
//        wrapper.eq(AddressBook::getUserId, BaseContext.getCurrentId());
//        wrapper.set(AddressBook::getIsDefault, 0);
        Long userId = (Long) session.getAttribute("user");

        addressBook.setUserId(userId);

        //SQL:update address_book set is_default = 0 where user_id = ?
        cqjdAddressBookService.updateAddressBookByUserId(addressBook);
//        addressBookService.update(wrapper);
//
//        addressBook.setIsDefault(1);
//        //SQL:update address_book set is_default = 1 where id = ?
//        addressBookService.updateById(addressBook);
        return R.ok();
    }


    /**
     * 查询默认地址
     */
    @GetMapping("/default")
    public R<CqjdAddressBook> getDefault(HttpSession session) {
//        LambdaQueryWrapper<AddressBook> queryWrapper = new LambdaQueryWrapper<>();
//        queryWrapper.eq(AddressBook::getUserId, BaseContext.getCurrentId());
//        queryWrapper.eq(AddressBook::getIsDefault, 1);


        Long userId = (Long) session.getAttribute("user");

        //SQL:select * from address_book where user_id = ? and is_default = 1
        CqjdAddressBook addressBook = cqjdAddressBookService.getDefaultAddressByUserId(userId);

        if (null == addressBook) {
            return R.fail("没有找到该对象");
        } else {
            return R.ok(addressBook);
        }
    }

    /**
     * 查询地址管理列表
     */
//    @PreAuthorize("@ss.hasPermi('cqjd:cqjd_address_book:list')")
    @GetMapping("/list")
    public TableDataInfo list(CqjdAddressBook cqjdAddressBook)
    {
        startPage();
        List<CqjdAddressBook> list = cqjdAddressBookService.selectCqjdAddressBookList(cqjdAddressBook);
        return getDataTable(list);
    }

    /**
     * 导出地址管理列表
     */
//    @PreAuthorize("@ss.hasPermi('cqjd:cqjd_address_book:export')")
    @Log(title = "地址管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, CqjdAddressBook cqjdAddressBook)
    {
        List<CqjdAddressBook> list = cqjdAddressBookService.selectCqjdAddressBookList(cqjdAddressBook);
        ExcelUtil<CqjdAddressBook> util = new ExcelUtil<CqjdAddressBook>(CqjdAddressBook.class);
        util.exportExcel(response, list, "地址管理数据");
    }

    /**
     * 获取地址管理详细信息
     */
//    @PreAuthorize("@ss.hasPermi('cqjd:cqjd_address_book:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(cqjdAddressBookService.selectCqjdAddressBookById(id));
    }

    /**
     * 新增地址管理
     */
//    @PreAuthorize("@ss.hasPermi('cqjd:cqjd_address_book:add')")
    @Log(title = "地址管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody CqjdAddressBook cqjdAddressBook)
    {
        return toAjax(cqjdAddressBookService.insertCqjdAddressBook(cqjdAddressBook));
    }

    /**
     * 修改地址管理
     */
//    @PreAuthorize("@ss.hasPermi('cqjd:cqjd_address_book:edit')")
    @Log(title = "地址管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody CqjdAddressBook cqjdAddressBook)
    {
        return toAjax(cqjdAddressBookService.updateCqjdAddressBook(cqjdAddressBook));
    }

    /**
     * 删除地址管理
     */
//    @PreAuthorize("@ss.hasPermi('cqjd:cqjd_address_book:remove')")
    @Log(title = "地址管理", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(cqjdAddressBookService.deleteCqjdAddressBookByIds(ids));
    }
}
